package com.huffman.smart_picture.common;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.RandomUtil;
import com.huffman.smart_picture.common.base.request.SendEmailRequest;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.domain.constants.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author DengLin
 * @title 邮箱相关服务
 * @date 2025/4/3
 */
@Component
@Slf4j
public class EmailService {
    @Value("${spring.mail.username}")
    private String from;// 发件人


    @Resource
    private JavaMailSender mailSender;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 邮件发送
     * @param sendEmailRequest
     * @return
     */
    public boolean sendEmail(SendEmailRequest sendEmailRequest) {
        String email = sendEmailRequest.getEmail();
        Integer emailType = sendEmailRequest.getEmailType();
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String cacheKey = RedisConstant.REGISTER_CHECK_CODE + ":" + email;
        String code = opsForValue.get(cacheKey);
        if (code != null) {
            throw new BusinessException(ErrorEnum.REQUEST_MANY, "请勿频繁发送验证码");
        }

        List<URL> resources = ResourceUtil.getResources("static/html/email-verification.html");
        URL resource = resources.get(0);
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer htmlFile = new StringBuffer();
        try {
            inputStreamReader = new InputStreamReader(resource.openStream(), StandardCharsets.UTF_8);
            reader = new BufferedReader(inputStreamReader);
            String line = null;
            while ((line = reader.readLine()) != null) {
                htmlFile.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        code = String.valueOf(RandomUtil.randomInt(100000, 999999));

        opsForValue.set(cacheKey,code,5, TimeUnit.MINUTES);

        String html = htmlFile.toString().replace("{}", code);

        return sendHtmlEmail(email, "用户注册", html);
    }

    private boolean sendHtmlEmail(String email, String subject, String html) {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject(subject);
            helper.setText(html, true);
            mailSender.send(message);

            log.info("发送邮件成功to:{}", email);
        } catch (MessagingException e) {
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR, "邮件发送失败,目标邮箱:" + email);
        }

        return true;
    }

    public static void main(String[] args) {
//        List<URL> resources = ResourceUtil.getResources("static/html/email-verification.html");
//        URL resource = resources.get(0);
//        System.out.println(resource.getFile());
    }
}
